package com.example.smartstart.controller;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.example.smartstart.model.Result;
import com.example.smartstart.entity.StudentInfo;
import com.example.smartstart.service.impl.StudentInfoServiceImpl;
import com.example.smartstart.utils.JwtUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("face/")
public class FaceController {

    @Autowired
    private StudentInfoServiceImpl studentInfoService;

    //设置APPID/AK/SK
    public static final String APP_ID = "95092286";
    public static final String API_KEY = "dsChv7GJJTk6QR9Gt7uyjzkU";
    public static final String SECRET_KEY = "ypY7sGbH4tgRGQFQq3lF0mgkuQSCccsJ";

    @PostMapping("login")
    public Result sample(String studentId, String photoUrl) {

        StudentInfo studentInfo = studentInfoService.getStudentInfoById(studentId);
        if (studentInfo == null) {
            return Result.error("学号错误");
        } else {
            String image1 = studentInfo.getPhoto();

            AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

            // 找到";base64,"的位置，并返回其后的字符串
            int startIndex = photoUrl.indexOf(";base64,") + ";base64,".length();
            String image2 = photoUrl.substring(startIndex);

            // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
            MatchRequest req1 = new MatchRequest(image1, "URL");
            MatchRequest req2 = new MatchRequest(image2, "BASE64");
            ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
            requests.add(req1);
            requests.add(req2);

            JSONObject res = client.match(requests);

            System.out.println(res.toString(2));

            Integer errorCode = res.getInt("error_code");
            String errorMsg = res.getString("error_msg");
            // 如果存在嵌套的JSON对象
            JSONObject resultObj = res.getJSONObject("result");
            double score = resultObj.getDouble("score");

            if (errorCode == 0) {
                if (score > 72.0) {
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("studentId", studentInfo.getStudentId());
                    String token = JwtUtil.genToken(claims);
                    return Result.success(token);
                } else {
                    return Result.error("识别未通过");
                }
            }else {
                return Result.error(errorMsg);
            }
        }
    }
}
